import 'package:flutter/material.dart';
import 'package:sweet_app/pages/chat/history_model.dart';

class ChatPage extends StatefulWidget {
  final HistoryModel historyModel;

  ChatPage({this.historyModel});

  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  List<String> _messages = ["我吃了", "Hello World", "即时通讯"];

  final TextEditingController _controller = TextEditingController();

  int _maxLines;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      int line = _controller.text.length ~/ 18;
      if (line == 0 && _maxLines != null) {
        setState(() {
          _maxLines = 1;
        });
      }
      if (line > 0 && line <= 3) {
        setState(() {
          _maxLines = line + 1;
        });
      }
    });
  }

  @override
    void didUpdateWidget(ChatPage oldWidget) {
      super.didUpdateWidget(oldWidget);
      print("更新Widget");
    }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.historyModel.friendName),
      ),
      body: Column(
        children: <Widget>[
          Expanded(child: _messageListWidget()),
          const Divider(height: 1.0),
          _inputWidget(),
        ],
      ),
    );
  }

  Widget _messageListWidget() {
    return ListView.builder(
      reverse: true,
      itemBuilder: (builder, index) {
        return MessageItemWidget(_messages[index]);
      },
      itemCount: _messages.length,
    );
  }

  Widget _inputWidget() {
    return Row(
      children: <Widget>[
        Expanded(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              controller: _controller,
              maxLines: _maxLines,
              keyboardType: TextInputType.multiline,
            ),
          ),
        ),
        IconButton(icon: Icon(Icons.send), onPressed: _sendMsg)
      ],
    );
  }

  void _sendMsg() {
    final text = _controller.text;
    if (text.isNotEmpty) {
      setState(() {
        _messages.insert(0, text);
        _controller.clear();
      });
    }
  }
}

class MessageItemWidget extends StatelessWidget {
  final String message;

  MessageItemWidget(this.message);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Flexible(
            child: Container(
              padding: const EdgeInsets.all(8.0),
              decoration: BoxDecoration(
                  color: Colors.lightGreen,
                  borderRadius: BorderRadius.circular(5.0)),
              child: Text(message, textAlign: TextAlign.start),
            ),
          ),
          const SizedBox(width: 8.0),
          CircleAvatar(child: Text("A")),
        ],
      ),
    );
  }
}
